package com.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.config.DynamicDataSource;
import com.test.entity.Tenant;
import com.test.mapper.TenantMapper;
import com.test.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    @DynamicDataSource("master")
    public Tenant createTenant(Tenant tenant) {
        // 生成数据库名
        String dbName = "tenant_" + UUID.randomUUID().toString().replace("-", "");
        tenant.setDbName(dbName);
        
        // 创建数据库
        jdbcTemplate.execute("CREATE DATABASE " + dbName);
        
        // 读取模板SQL文件
        try {
            String templateSql = new String(Files.readAllBytes(Paths.get("tenant_template.sql")));
            // 替换数据库名
            templateSql = templateSql.replace("${dbName}", dbName);
            
            // 执行SQL创建表结构
            String[] sqlStatements = templateSql.split(";");
            for (String sql : sqlStatements) {
                if (!sql.trim().isEmpty()) {
                    jdbcTemplate.execute(sql);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to read template SQL file", e);
        }
        
        // 保存商户信息
        save(tenant);
        return tenant;
    }

    @Override
    @DynamicDataSource("master")
    public Tenant getTenantByCode(String tenantCode) {
        return lambdaQuery().eq(Tenant::getTenantCode, tenantCode).one();
    }
} 